# -*- coding: utf-8 -*-

#    Copyright (C) 2014 by Promotux
#                       di Francesco Meloni snc - http://www.promotux.it/

#    Author: Francesco Meloni  <francesco@promotux.it>

#    This file is part of OdCollect.

#    OdCollect is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 2 of the License, or
#    (at your option) any later version.

#    OdCollect is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with OdCollect.  If not, see <http://www.gnu.org/licenses/>.

import hashlib
import datetime
from web_lib.page import Page
from web_lib.webutils import *
from web_lib.MailHandler import SendMail
import Environment
from dao.User import User
from dao.Setconf import SetConf
from dao.Role import Role
from lib.utils import prep2json

@expose('/usernameCheck')
def usernameCheck(req, static=None, subdomain=None):
    fieldValue = req.args.get('fieldValue')
    fieldId = req.args.get('fieldId')
    us = User().select(username=fieldValue)
    if us:
        esito = False
    else:
        esito = True
    item = [fieldId,esito]
    jasoned = json.dumps(item)
    return Response(jasoned)

@expose('/emailCheck')
def emailCheck(req, static=None, subdomain=None):
    fieldValue = req.args.get('fieldValue')
    fieldId = req.args.get('fieldId')
    us = User().select(emailEM=fieldValue)
    if us:
        esito = False
    else:
        esito = True
    item = [fieldId,esito]
    jasoned = json.dumps(item)
    return Response(jasoned)

@expose('/captchaCheck')
def captchaCheck(req, static=None, subdomain=None):
    fieldValue = req.args.get('fieldValue')
    fieldId = req.args.get('fieldId')
    captchamd5 = hashlib.md5(fieldValue).hexdigest()
    if captchamd5 != fieldId:
        esito = False
    else:
        esito = True
    item = [fieldId,esito]
    jasoned = json.dumps(item)
    return Response(jasoned)

@expose('/userRegistration')
def userRegistration(req, static=None, subdomain=None):
    """ USER:[u'id', u'username', u'password', u'email',
        u'registration_date', u'last_modified', u'photo_src',
        u'id_role', u'active', u'schemaa_azienda', u'tipo_user',
        u'id_language', u'email_confirmed', u'mailing_list', u'privacy']
    """

    if req.args.get('new') =="":
        username = req.form.get('username')
        password = req.form.get('password')
        regione = req.form.get('regione')

        user = User()
        user.username = username
        user.password = hashlib.md5(username + \
                                password).hexdigest()
        user.email = req.form.get('email')
        user.mailing_list = req.form.get('mailing_list') or False
        user.privacy = req.form.get('privacy') or False
        user.registration_date = datetime.datetime.now()
        user.id_language = 1
        user.tipo_user = "PgWeb"
        ruolo = Role().select(name="Cliente")
        if ruolo:
            idrole= ruolo[0].id
        else:
            idrole = 2
        user.id_role = idrole
        user.active = True
        user.schemaa_azienda = Environment.params["schema"]
        user.persist()
        """CLIENTE:id id_pagamento id_magazzino id_listino id_banca
            pagante id_aliquota_iva tipo
            PERSONA GIURIDICA: id codice ragione_sociale
            insegna cognome nome sede_operativa_indirizzo
            sede_operativa_cap sede_operativa_provincia
            sede_operativa_localita sede_legale_indirizzo
            sede_legale_cap sede_legale_provincia sede_legale_localita
            nazione codice_fiscale partita_iva id_user note cancellato
        """

        d = Cliente()
        d.tipo = "PG"
        d.codice = getNuovoCodiceCliente()
        d.ragione_sociale = str(req.form.get("ragione_sociale"))
        d.cognome = str(req.form.get("cognome"))
        d.nome = str(req.form.get("nome"))
        d.nazione = str(req.form.get("nazione"))
        d.codice_fiscale = str(req.form.get("codice_fiscale"))
        d.partita_iva = str(req.form.get("partita_iva"))
        d.note =  str(req.form.get("note"))
        d.sede_legale_cap =  str(req.form.get("sede_legale_cap"))
        d.sede_legale_indirizzo =  str(req.form.get("sede_legale_indirizzo"))
        d.sede_legale_provincia = str(req.form.get('provincia'))
        d.sede_legale_localita = str(req.form.get('citta'))
        d.id_user = user.id
        d.persist()
        dao_contatto = ContattoCliente()
        appa = ""
        if d.ragione_sociale:
            appa = d.ragione_sociale
        if d.cognome:
            appa = appa+" " +d.cognome
        dao_contatto.cognome = appa
        if d.nome:
            dao_contatto.nome = d.nome
        dao_contatto.tipo_contatto ="cliente"
        dao_contatto.id_cliente = d.id
        dao_contatto.persist()

        reco = RecapitoContatto()
        reco.id_contatto = dao_contatto.id
        reco.tipo_recapito = "Cellulare"
        reco.recapito = req.form.get("cliente_cellulare_principale")
        reco.persist()

        reco = RecapitoContatto()
        reco.id_contatto = dao_contatto.id
        reco.tipo_recapito = "Telefono"
        reco.recapito = req.form.get("telefono_principale")
        reco.persist()

        reco = RecapitoContatto()
        reco.id_contatto = dao_contatto.id
        reco.tipo_recapito = "Email"
        reco.recapito = req.form.get("email")
        reco.persist()

        recow = RecapitoContatto()
        recow.id_contatto = dao_contatto.id
        recow.tipo_recapito = "Sito"
        recow.recapito = req.form.get('url')
        recow.persist()

        reco = RecapitoContatto()
        reco.id_contatto = dao_contatto.id
        reco.tipo_recapito = "Fax"
        reco.recapito = req.form.get("fax_principale")
        reco.persist()
        #pg.persist()
        #if SetConf().select(key="self_confirm")[0].value:
            #SendMail(req=req,to=email).sendRegisterCodeToUser(userid=user.id)
            #SendMail(req=req,to="me").sendRegisterUser()
            #pageData = {'file' : 'registerCodeSent'}
        #else:
            #SendMail(req=req, to=email).sendRegisterUser()
            #pageData = {'file' : 'registerConfirmed'}
        #redirectUrl="/"
        #return Page(req).redirect(redirectUrl)
        pageData = {'file' : 'main/registerConfirmed'}
        return Page(req).render(pageData)
    else:
        province = Province().select(batchSize=None)
        regioni = Regioni().select(batchSize=None)
        string = createcaptcha()
        pageData = {'file' : 'main/userRegistration',
                    "province":province ,
                    "regioni" :regioni,
                    'string':hashlib.md5(string).hexdigest(),
                    'sent' : "False"}
    return Page(req).render(pageData)
